<?php
namespace app\front\service\v1;
use think\Session;
use app\front\service\GetMsgService;
use app\front\service\v1\Notify as NotifyService;
use app\front\model\Sharehongbao as SharehongbaoModel;
use app\front\model\Order as OrderModel;
use app\front\model\Userinfo as UserinfoModel;
use app\front\model\Filiale as FilialeModel;
use app\front\model\Discount as DiscountModel;
use app\front\model\Award as AwardModel;
use app\front\model\Awardrecord as AwardrecordModel;
class ShareWx extends GetMsgService
{
    public  function shareWx(){
        $out_trade_no= input('param.out_trade_no');
        $TemporaryMsg=$this->getTemporaryForMchId($out_trade_no);
        $customer_id=$TemporaryMsg['open_id'];
        $store_id =$TemporaryMsg['store_id'];
        $moneyNum = $TemporaryMsg['total_fee'];
        $moneyNum= bcdiv($moneyNum,100,2);
        
        $user=getMemberMessageForOpenid($customer_id);
        $nickname=$user['nickname'];
        $userinfo=$this->getUserinfoForOpenid($user['openid']);
        $userid=  $userinfo['id'];
        
        $store=$this->getStoreForStoreid($store_id);
        $shop_id= $store['shop_id'];
        $store_name =$store['store_name'];
        $imgurl =$store['imgurl']; 
        $phone =$store['phone']; 
        $address =$store['address']; 
       
       
       
        $redPacket= AwardrecordModel::where('mch_billno',$out_trade_no)->field('award_money')->find();
        $red_packet=$redPacket['award_money'];
        $red_packet= round($red_packet,2);
        
        
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url="$_SERVER[REQUEST_URI]";
        $url=substr($url,1);
        $url = "http://www.zfshlm.com/098f6bcd4621d373cade4e832627b4f6".$url;
       // $url=config('shareWxURL').'?out_trade_no='.$out_trade_no;
        $jsapiTicket = getJsApiTicket();
        $timestamp = time();
        $nonceStr = createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
       
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        
        $shareData=[
            'imgurl'=> $imgurl,
            'userid'=> $userid,
            'moneyNum'=> $moneyNum,
            'red_packet'=>  $red_packet,
            'store_name'=> $store_name,
            'phone'=>$phone,
            'address'=> $address,
            'timestamp'=>$timestamp,
            'nonceStr'=> $nonceStr,
            'signature'=> $signature,
            'out_trade_no'=> $out_trade_no
        ];
        return $shareData;
    }
    
   
    /**
     * 函数用途描述 :
     * @date: 2018年2月2日 下午11:39:02
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function HongBaoForShare(){
        $out_trade_no=input('param.out_trade_no');
        $OrderMsg=$this->getOrderMsgForID($out_trade_no);
        $store_id=$OrderMsg['store_id'];
        $store=$this->getStoreForStoreid($store_id);
        $store_name=$store['store_name'];
        $redPackMsg=$this->getRedpackMsgForID($out_trade_no);
        $red_packet=$redPackMsg['award_money'];
        $moneyNum= $OrderMsg['money'];
        $shop_id= $OrderMsg['shop_id'];
        $filiale_id= $OrderMsg['filiale_id'];
        $openid=$OrderMsg['customer_id'];
       // logs("OrderMsg.txt", $red_packet);
        if($moneyNum<config('defaultNum')){
            $red_packet=0;
        }else{
            //总消费金额的百分之三X百分之一百二
            $red_packet = bcmul($moneyNum,0.025,5);
            $red_packet=bcmul($red_packet,config('shareHongBaoPercent'),2);
            if($red_packet<0.3){
                $red_packet=0.3;
            }
        }
      //  logs("OrderMsg.txt", $red_packet);
        $mch_billno=makeOrderNo();
        $todayAlreadyShare=$this->TodayisExistShareHongBao($openid);
        $todayAleadyPay=$this->isExistOrder($openid);
        $params=$this->getShareHbXmlParams($mch_billno, $red_packet, $store_name,$openid);
        if(!$todayAlreadyShare &&  $todayAleadyPay){
            $retuen_params=postStr(config('HONGBAOURL'),$params);
            logs('log_return_HongBaoForShare.txt',$retuen_params);
            $retuen_params=XmlToArr($retuen_params);
            if($retuen_params['return_code'] == 'SUCCESS' && $retuen_params['result_code'] == 'SUCCESS'){
                $record_data = ['mch_billno'=>$mch_billno,'msg'=>$retuen_params['return_msg'],'customer_id'=>$openid,'store_id'=> $store_id,'order_money'=>$money,'award_money'=>$red_packet,'create_time'=>date("Y-m-d H:i:s",time()),'record_statu'=>1,'purpose'=>2,'shop_id'=>$shop_id,'filiale_id'=>$filiale_id];
                AwardrecordModel::create($record_data);
                $this->changeShareNum($openid);
                if(!$todayAlreadyShare){
                    $this->shareHongBaoAdd($mch_billno, $openid,$red_packet);
                }
                return 'ShareSuccess';
            }else{
                return 'ShareFail'; 
            }
            
        }else{
           logs("HongBaoForSHARE.txt", "今天未支付或者已分享过");
            return 'ShareFail'; 
        }
        
        
        
    }
    
    
    /**
     * 函数用途描述 : 判断用户今天是否领过红包
     * @date: 2018年2月3日 上午1:03:22
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function TodayisExistShareHongBao($openid){
        $isExist=0;
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
        $res=  SharehongbaoModel::where("create_time >='$starttime' and create_time <='$endtime'")->select();
        foreach( $res as $v )
        { //存在且金额大于0.3才算有效分享
            if(strcmp($openid,$v['openid'])==0){
                if($v['money']>=0.3){
                    $isExist=1;
                    break;
                }
                
            }
        }
        
        return $isExist;
        
    }
    
    
    /**
     * 函数用途描述 : 判断用户是否消费过
     * @date: 2018年2月3日 上午1:03:22
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function isExistOrder($openid){
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
        $isExist=0;
        $res= OrderModel::where("create_time >='$starttime' and create_time <='$endtime'")->select();
        foreach( $res as $v )
        {
            if(strcmp($openid,$v['customer_id'])==0){
                $isExist=1;
                break;
            }
        }
        return $isExist;
    }
    
    
    /**
     * 函数用途描述 :更改userinfo下的shareNum
     * @date: 2018年2月26日 下午8:00:50
     * @author: 孙洪亮
     * @param:  null
     * @return: null
     */
    public function changeShareNum($openid){
       // $openid="'".$openid."'";
        $Share =  UserinfoModel::where('openid',$openid)->field('shareNum')->find();
        $ShareNum =$Share['shareNum'];
        $newShareNum['shareNum']=$ShareNum+1;
        UserinfoModel::where('openid',$openid)->update($newShareNum);           
    }
    
    /**
     * 函数用途描述 :当用户分享领红包后记录到数据库中
     * @date: 2018年2月3日 上午1:03:51
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function shareHongBaoAdd($mch_billno,$openid,$money){
        $params=[
            'id'=> $mch_billno,
            'openid'=>$openid,
            'money'=>$money,
            'create_time'=>date("Y-m-d H:i:s",time()),
        ];
        $res= SharehongbaoModel::create($params);
        return $res;
    }
    
    /**
    
    * 函数用途描述:获取红包返红包所用的xml数据
    
    * @param: $mch_billn 商户订单号,$red_packet（红包金额 分度值：分）
    
    * @return:返回XML字符串
    
    */
    public function  getShareHbXmlParams($mch_billno,$red_packet,$store_name, $customer_id){
        
        $params = [
            'nonce_str' => createNonceStr(),//随机字符串
            'mch_billno' =>$mch_billno,//商户订单号
            'mch_id' =>config('mch_id'),//商户号
            'wxappid' =>config('appid'),//公众账号appid
            'send_name' =>$store_name,//商户名称
            're_openid' => $customer_id,//用户openid
            'total_amount' =>$red_packet*100,//红包金额
            'total_num' =>1,//红包发放总人数
            'wishing' =>config('wishing'),//红包祝福语
            'client_ip' =>'47.93.11.60',// 调用接口的机器Ip地址
            'act_name' =>config('act_name'),//活动名称
            'remark' => config('remark'),//备注信息
            'scene_id'=>'PRODUCT_1' //场景ID PRODUCT_5:渠道分润
        ];
        $params['sign'] = getSign($params);//加入签名
        return ArrToXml($params);
    }
    
}

